package com.linkturing.swing;

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Set;

import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

import com.alibaba.fastjson.JSON;
import com.linkturing.util.Constants;
import com.linkturing.util.JedisUtil;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

public class DataTable {

	
    private String head[] = null;
    private Object [][]data = null;
    
    JButton delButton = new JButton("刪除");
	
	JButton editButton = new JButton("編輯");
	
	DefaultTableModel tableModel = null;
	
	ActionPanelEditorRenderer er = null;
    
	public DataTable(String key) {
		
        head = new String[] {
            "#", "计量日期", "卷号", "分卷号", "重量", "长度", "规格", "发送标记", "操作",
        };
        Object[][] dataList = queryData(key);
        JTable table = new JTable();
        
        table.setBorder(new LineBorder(new Color(0, 0, 0)));
        
		  tableModel = new DefaultTableModel(dataList,head){ 
			@Override
			public boolean isCellEditable(int row, int column) {
			  if(column==8) { return true; } 
			  return false; 
			} 
		  }; 
		  
		  table.setModel(tableModel);
		 
        table.setRowHeight(36);
		
        XinhuaApplication.scrollPane.setViewportView(table);
        XinhuaApplication.table = table;

	}
	
	
	public void reloadTable(String key) {
        
        JTable table = XinhuaApplication.table;
         
        table.setBorder(new LineBorder(new Color(0, 0, 0)));
        head = new String[] {
            "#", "计量日期", "卷号", "分卷号", "重量(kg)", "长度(m)", "规格", "发送标记", "操作",
        };
        
        Object[][] dataList = queryData(key);
        
        	tableModel = new DefaultTableModel(dataList,head){
    			private static final long serialVersionUID = 1L;
    			
    			@Override
				public boolean isCellEditable(int row, int column)
                {
    				if(column==8) {
    					return true;
    				}
                    return false;
                }
            };
        table.setModel(tableModel);
        table.setRowHeight(36);
		
		  if(dataList!=null) { 
			  if(er==null) {
				  er = new ActionPanelEditorRenderer(key); 
			  }
			  
			  TableColumn column =  table.getColumnModel().getColumn(8); 
			  column.setCellRenderer(er);
		      column.setCellEditor(er); 
		   }
		 
		 
        XinhuaApplication.scrollPane.setViewportView(table);
	}
	
	//生成表格数据
    /**
     * @return
     */
    public Object[][] queryData(String key){
        List<LtProductQualityBasic> list = new ArrayList<LtProductQualityBasic>();

		List<String> jsonList = new ArrayList<String>();
        if(key!=null){
//			jsonList = JedisUtil.getList(key);
        	Set<String> keys = JedisUtil.keys(key);
			for (String s : keys) {
				System.out.println(s);
				List<String> list1 = JedisUtil.getList(s);
				if(list1!=null && list1.size()>0){
					jsonList.addAll(list1);
				}
			}
		}else {
			Set<String> keys = JedisUtil.keys("*-*:weight:*");
			for (String s : keys) {
				System.out.println(s);
				List<String> list1 = JedisUtil.getList(s);
				if(list1!=null && list1.size()>0){
					jsonList.addAll(list1);
				}
			}
		}
        
        System.out.println("qqw:"+jsonList);
        
        if(jsonList!=null) {
        	for(int i=0;i<jsonList.size();i++) {
        		String json = jsonList.get(i);
        		LtProductQualityBasic bean = JSON.toJavaObject(JSON.parseObject(json), LtProductQualityBasic.class);
        		list.add(bean);
        	}
        	//排序
        	Collections.sort(list, new Comparator<LtProductQualityBasic>()
            {
                public int compare(LtProductQualityBasic pqb1, LtProductQualityBasic pqb2)
                {
                    if(pqb1.getCreateDate().equals(pqb2.getCreateDate())){
                    	if(pqb2.getReelNumber().equals(pqb1.getReelNumber())) {
                    		return Integer.parseInt(pqb2.getVolumeNumber())-Integer.parseInt(pqb1.getVolumeNumber());
                    	}
                        return new BigDecimal(pqb2.getReelNumber()).compareTo(new BigDecimal(pqb1.getReelNumber()));
                    } else {
                    	
                        return DateUtil.compare(DateUtil.parse(pqb2.getCreateDate()), DateUtil.parse(pqb1.getCreateDate()));
                    }
                }
            });

        	data = new Object[list.size()][head.length];
            for(int i=0;i<list.size();i++){
                for(int j=0;j<head.length;j++){
                    data[i][0]=String.valueOf(i+1);
                    data[i][1]=list.get(i).getCreateDate();
                    data[i][2]=list.get(i).getReelNumber();
                    data[i][3]=list.get(i).getVolumeNumber();
                    data[i][4]=list.get(i).getWeight();
                    data[i][5]=list.get(i).getLength();
                    data[i][6]=list.get(i).getSpecs();
                    data[i][7]=!"1".equals(list.get(i).getSendFlag())?"未发送":"已发送";
                    if("2".equals(list.get(i).getSendFlag())) {
                    	data[i][7]= "卷号以及分卷号已存在！";
                    }
                }
            }
            
        }
        
        return data;
    }
    
	class ActionPanelEditorRenderer extends AbstractCellEditor implements TableCellRenderer, TableCellEditor {
		private static final long serialVersionUID = 1L;
		JPanel panel1 = new JPanel();
		JPanel panel2 = new JPanel();

		public ActionPanelEditorRenderer(String key) {
			super();

			panel2.add(delButton);
			panel2.add(editButton);
			delButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int i = XinhuaApplication.table.getSelectedRow();
					String date = (String)XinhuaApplication.table.getModel().getValueAt(i, 1);
					String juanhao = (String)XinhuaApplication.table.getModel().getValueAt(i, 2);
					String fenjuanhao = (String)XinhuaApplication.table.getModel().getValueAt(i, 3);
					System.out.println("date="+date+";juanhao="+juanhao);
					
					JedisUtil.del(date+":"+Constants.weight+":"+juanhao, fenjuanhao);
					JOptionPane.showMessageDialog(null, "刪除成功");
					
					juanhao = XinhuaApplication.textField.getText();
					if(StrUtil.isBlank(juanhao)) {
						juanhao = "*";
					}
					
					String key = XinhuaApplication.txt1.getText()+":"+Constants.weight+":"+juanhao;
					System.out.println("key="+key);
					XinhuaApplication.dataTable.reloadTable(key);
					
				}
			});

			editButton.addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					int i = XinhuaApplication.table.getSelectedRow();
					String date = (String) tableModel.getValueAt(i,1);
					String juanhao = (String) tableModel.getValueAt(i, 2);
					String fenjuanhao = (String) tableModel.getValueAt(i, 3);
					String weight = String.valueOf(tableModel.getValueAt(i, 4));
					String length = String.valueOf(tableModel.getValueAt(i, 5));
					String spec = String.valueOf(tableModel.getValueAt(i, 6));
					String flag = String.valueOf(tableModel.getValueAt(i, 7));
					if("已发送".equals(flag)) {
						JOptionPane.showMessageDialog(null, "已发送不能编辑！");
					}
					else {
						WeightingEdit frame = new WeightingEdit(juanhao, fenjuanhao, weight,length,spec,i,date);
						frame.setVisible(true);
						frame.setAlwaysOnTop(true);
					}
				}
			});
		}

		@Override
		public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus,
				int row, int column) {
			panel2.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());
			panel2.setBackground(isSelected ? table.getSelectionBackground() : table.getBackground());

			return panel2;
		}

		@Override
		public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row,
				int column) {
			panel2.setBackground(table.getSelectionBackground());
			return panel2;
		}

		@Override
		public Object getCellEditorValue() {
			return null;
		}
	}
}
